package com.github.alenfive;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class AnalysisUtils {

    public static Logger logger = LoggerFactory.getLogger(AnalysisUtils.class);

    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    }

    private static boolean debugAnalysisOpen = true;

    @Value("${debug.analysis.open: true}")
    public void setDebugAnalysisOpen(boolean open) {
        AnalysisUtils.debugAnalysisOpen = open;
    }

    public static void printStackTrace() {
        if (debugAnalysisOpen) {
            try {
                throw new RuntimeException("打印堆栈信息，方便调试");
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    public static void printStackTraceMsg(String msg) {
        if (debugAnalysisOpen) {
            try {
                throw new RuntimeException(msg);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    public static void printStackTraceObj(Object obj) {
        if (debugAnalysisOpen) {
            try {
                if (obj==null) {
                    throw new RuntimeException();
                }
                throw new RuntimeException(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    public static void printRequestDataParams() {
        if (debugAnalysisOpen) {
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            if (attributes!=null) {
                printRequestDataParams(((ServletRequestAttributes) attributes).getRequest());
            }
        }
    }

    public static void printRequestDataParams(HttpServletRequest request) {
        if (debugAnalysisOpen) {
            if (request != null) {
                StringBuffer sb = new StringBuffer("\n\n" + request.getRequestURI());
                Map<String, String> requestUrlParams = (Map<String, String>) request.getAttribute("requestUrlParams");
                sb.append("\n\trequestUrlParams" + JSON.toJSONString(requestUrlParams, SerializerFeature.MapSortField, SerializerFeature.PrettyFormat) + "\n");
                Map<String, String> requestHeaderParams = (Map<String, String>) request.getAttribute("requestHeaderParams");
                sb.append("\trequestHeaderParams" + JSON.toJSONString(requestHeaderParams, SerializerFeature.MapSortField, SerializerFeature.PrettyFormat) + "\n");
                Object requestBodyData = request.getAttribute("requestBodyData");
                if (requestBodyData != null) {
                    sb.append("\trequestBodyData" + JSON.toJSONString(requestHeaderParams, SerializerFeature.MapSortField, SerializerFeature.PrettyFormat) + "\n");
                }
                logger.error(sb.toString());
            }
        }
    }
}
